package com.hn.demo.action;

import com.hn.demo.service.IModifyService;
import com.hn.demo.service.IQueryService;
import com.hn.springframework.annotation.HNAutowired;
import com.hn.springframework.annotation.HNController;
import com.hn.springframework.annotation.HNRequestMapping;
import com.hn.springframework.annotation.HNRequestParam;
import com.hn.springframework.webmvc.servlet.HNModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


@HNController
@HNRequestMapping("/web")
public class MyAction {

	@HNAutowired
	IQueryService queryService;
	@HNAutowired
	IModifyService modifyService;

	@HNRequestMapping("/query.json")
	public HNModelAndView query(HttpServletRequest request, HttpServletResponse response,
								@HNRequestParam("name") String name){
		String result = queryService.query(name);
		return out(response,result);
	}
	
	@HNRequestMapping("/add*.json")
	public HNModelAndView add(HttpServletRequest request, HttpServletResponse response,
                              @HNRequestParam("name") String name, @HNRequestParam("addr") String addr){
		String result = null;
		try {
			result = modifyService.add(name,addr);
			return out(response,result);
		} catch (Exception e) {
//			e.printStackTrace();
			Map<String,Object> model = new HashMap<String,Object>();
			model.put("detail",e.getCause().getMessage());
//			System.out.println(Arrays.toString(e.getStackTrace()).replaceAll("\\[|\\]",""));
			model.put("stackTrace", Arrays.toString(e.getStackTrace()).replaceAll("\\[|\\]",""));
			return new HNModelAndView("500",model);
		}

	}
	
	@HNRequestMapping("/remove.json")
	public HNModelAndView remove(HttpServletRequest request, HttpServletResponse response,
                                 @HNRequestParam("id") Integer id){
		String result = modifyService.remove(id);
		return out(response,result);
	}
	
	@HNRequestMapping("/edit.json")
	public HNModelAndView edit(HttpServletRequest request, HttpServletResponse response,
                               @HNRequestParam("id") Integer id,
                               @HNRequestParam("name") String name){
		String result = modifyService.edit(id,name);
		return out(response,result);
	}
	
	
	
	private HNModelAndView out(HttpServletResponse resp, String str){
		try {
			resp.getWriter().write(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
